package com.huawei.servlet;

import com.huawei.bean.User;
import com.huawei.dao.UserDao;
import com.huawei.util.DateTools;
import org.apache.catalina.realm.UserDatabaseRealm;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用于处理表单中提交过来的信息
 * 将信息转化为User对象 并传入数据库
 */
@WebServlet(value = "/insert.do")
public class InsertServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码格式 防止乱码
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取表单中的信息
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        //接收到的是一个数组
        String[] hobbies = req.getParameterValues("hobbies");
        //User对象赋值
        User user = new User();
        user.setName(name);
        //字符串转数字
        //前提是字符串不为空  也不为空串
        if (age!=null && age!=""){
            int nl = Integer.parseInt(age);
            user.setAge(nl);
        }else{
            user.setAge(18);
        }
        //性别是字符串转char 取第一个
        user.setGender(gender.charAt(0));
        user.setBirthday(DateTools.dataStrToDate(birthday));
        user.setHobbies(hobbies);
        //失败返回 0 未失败返回1 (插入数据库中)
        if (UserDao.insertUser(user)>=1){
            resp.getWriter().println("数据已录入");
        }else{
            resp.getWriter().println("数据录入失败");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
